package cn.com.doone.common.uc.oauth.authorize;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import cn.com.doone.common.uc.oauth.OAuthAuthxRequest;
import cn.com.doone.common.uc.oauth.validator.AbstractClientDetailsValidator;
import cn.com.doone.common.uc.oauth.validator.ExistTokenClientDetailValidator;
import cn.com.doone.common.uc.utils.HttpClientUtil;
import cn.com.doone.common.uc.utils.StringUtils;
import cn.com.doone.common.uc.web.WebUtils;

public class ExistTokenAuthorizeHandler extends AbstractAuthorizeHandler {
	
	private static final Logger LOG = LoggerFactory.getLogger(ExistTokenAuthorizeHandler.class);

	public ExistTokenAuthorizeHandler(OAuthAuthxRequest oauthRequest, HttpServletResponse response) {
		super(oauthRequest, response);
	}
	
	public ExistTokenAuthorizeHandler(OAuthAuthxRequest oauthRequest, HttpServletResponse response,HttpServletRequest request) {
		super(oauthRequest, response,request);
	}
	
	@Override
	protected AbstractClientDetailsValidator getValidator() {
		return new ExistTokenClientDetailValidator(oauthRequest,request);
	}
	
	@Override
	public void handle() throws Exception {
		// 认证IP锁
        if (validIpLock()) {
        	return;
        }
    	
        // validate
        if (validateFailed()) {
            return;
        }
        
        //handle response
        handleResponse();
        
	}
	
	@Override
	protected void handleResponse() throws OAuthSystemException, IOException {
		
		// 获取跳转地址
		final String redirectURI = HttpClientUtil.decodeURIComponent(HttpClientUtil.decodeURIComponent(oauthRequest.getRedirectURI()));
		
		// 获取token
		String token = StringUtils.isNull(oauthRequest.getParam("token"))?request.getHeader("token"):oauthRequest.getParam("token");
		
		// 根据token获取username
		Map<String, Object> infoMap = oauthService.queryInfoByToken(token);
		if (StringUtils.isNull(infoMap)) {
			OAuthResponse.errorResponse(HttpServletResponse.SC_NOT_FOUND)
					.setError(OAuthError.CodeResponse.INVALID_REQUEST).setErrorDescription("invalid_request")
					.buildJSONMessage();
		}
		
		infoMap.put("client_id", oauthRequest.getClientId());
		
		//获取code
		String authCode = oauthService.retrieveAuthCode(infoMap);
		
		final OAuthResponse oAuthResponse = OAuthASResponse
                .authorizationResponse(oauthRequest.request(), HttpServletResponse.SC_OK)
                .location(redirectURI)
                .setCode(authCode)
                .buildQueryMessage();

		//写app日志
		Map<String,Object> loggerMap = new HashMap<String,Object>();
		loggerMap.put("login_account", infoMap.get("username"));
		loggerMap.put("login_type", "third-party application");
		loggerMap.put("login_app", clientId());
		loggerMap.put("is_success", true);
		loggerMap.put("reason", 0);
		LOG.info(loggerMap.toString());
		
        WebUtils.writeOAuthQueryResponse(response, oAuthResponse);
	}
}
